package top.huhuiyu.springboot.study.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.huhuiyu.springboot.study.config.MxnzpConfig;
import top.huhuiyu.springboot.study.entity.joke.JokeInfo;
import top.huhuiyu.springboot.study.entity.joke.TbJoke;
import top.huhuiyu.springboot.study.mapper.joke.JokeMapper;
import top.huhuiyu.springboot.study.service.JokeService;
import top.huhuiyu.springboot.study.util.JsonUtils;

/**
 * @author 胡辉煜
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class JokeServiceImpl implements JokeService {
  private final RestTemplate restTemplate;
  private final JokeMapper jokeMapper;

  @Override
  public JokeInfo getJoke() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("app_id", MxnzpConfig.APPID);
    headers.add("app_secret", MxnzpConfig.APPSECRET);
    HttpEntity<String> entity = new HttpEntity<>("", headers);
    String result = restTemplate.exchange(MxnzpConfig.JOKE_RANDOM_URL, HttpMethod.GET, entity, String.class).getBody();
    return JsonUtils.parse(result, JokeInfo.class);
  }

  @Override
  public int saveJoke() {
    JokeInfo jokeInfo = getJoke();
    jokeInfo.getData().forEach(joke -> {
      TbJoke info = new TbJoke();
      info.setContent(joke.getContent());
      info.setUpdateTime(joke.getUpdateTime());
      jokeMapper.insert(info);
    });
    return jokeInfo.getData().size();
  }


}
